package com.graduation.interceptor;

import com.graduation.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 该函数制作访问服务器之前的拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取客户端的cookie
            Cookie[] cookies = request.getCookies();
            String autoLogin = null;
            for (int i = 0; cookies != null && i < cookies.length; i++) {
                if ("autoLogin".equals(cookies[i].getName())) {
                    autoLogin = cookies[i].getValue();
                    break;
                }
            }
            if (autoLogin != null) {
                //将value值分割存入数据
                String[] parts = autoLogin.split("-");
                String email = parts[0];
                String password = parts[1];
                //存入User对象
                User user = new User();
                user.setEmail(email);
                user.setPassword(password);
                request.getSession().setAttribute("user", user);
                return true;
            }
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            User users = (User) request.getSession().getAttribute("user");
            if (users == null) {
                response.sendRedirect("login.do");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        return false;
    }
}
